<template>
  <Form ref="addFrom" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
    <FormItem label="会议室名称：" prop="name">
      <Input v-model="form.name" placeholder="请输入名称"></Input>
    </FormItem>
    <FormItem label="会议室容量：" prop="capacity">
      <Input v-model="form.capacity" placeholder="请输入容量"></Input>
    </FormItem>
    <FormItem label="会议室地址：" prop="address">
      <Input v-model="form.address" placeholder="请输入地址"></Input>
    </FormItem>
    <FormItem v-if="isTeam" label="所属团队编号：" prop="address">
      <Input v-model="form.team_id" placeholder="请输入团队编号"></Input>
    </FormItem>
    <FormItem label="支持设备：" v-if="isDevice">
      <div style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
        <Checkbox
          :indeterminate="checkOption.indeterminate"
          :value="checkOption.checkAll"
          @click.prevent.native="handleCheckAll"
        >全选</Checkbox>
      </div>
      <CheckboxGroup v-model="form.equip" @on-change="checkAllGroupChange">
        <Checkbox
          v-for="(item) in equipData"
          :key="item.device_id"
          :label="item.device_id"
          :value="item.device_id"
          size="large"
          @on-change="checkAllGroupChange"
        >
          <span>{{item.device_name}}</span>
        </Checkbox>
      </CheckboxGroup>
    </FormItem>
    <FormItem label="预约审核：">
      <i-switch size="large" v-model="form.ischeck" @on-change="ischeckChange">
        <span slot="open">启用</span>
        <span slot="close">停用</span>
      </i-switch>
    </FormItem>
    <FormItem label="上传缩略图（600*200）：">
      <br>
      <div class="avator">
        <img :src="photoImg">
      </div>
      <Upload
        type="drag"
        name="photoFile"
        :action="upPhoto.url"
        :headers="upPhoto.headers"
        :show-upload-list="false"
        accept="image"
        :format="['jpg','jpeg','png','gif']"
        :max-size="20480"
        :before-upload="handleUploadBefore"
        :on-success="handleUploadSuccess"
        :on-format-error="handleUploadErr"
        :on-exceeded-size="handleUploadMaxSize"
        :style="{width:'80%',float:'right'}"
      >
        <div style="padding: 20px 0">
          <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
          <p>点击或者将文件拖进来上传</p>
        </div>
      </Upload>
    </FormItem>
    <FormItem label="状态：">
      <i-switch size="large" v-model="form.state" @on-change="stateChange">
        <span slot="open">启用</span>
        <span slot="close">停用</span>
      </i-switch>
    </FormItem>
    <FormItem>
      <div style="width:80%;margin:0 auto;">
        <Button type="primary" :loading="submit" @click="handleSubmit" long>
          <span v-if="!submit">确定创建</span>
          <span v-else>创建中...</span>
        </Button>
      </div>
    </FormItem>
  </Form>
</template>

<style lang="less" scoped>
.avator {
  height: 126px;
  width: 19%;
  float: left;
  img {
    margin: 0 auto;
    margin-top: 13px;
    height: 100px;
    width: 100%;
  }
}
</style>

<script>
import config from '@/config'
import { jwtToken, getImage, getIsTeam } from '@/libs/util'
import { getDeviceArr } from '@/api/meet'

const baseUrl =
  process.env.NODE_ENV === 'development'
    ? config.baseUrl.dev
    : config.baseUrl.pro
export default {
  name: 'addFrom',
  props: {
    nameRules: {
      type: Array,
      default: () => {
        return [
          {
            required: true,
            message: '会议室名称不能为空',
            trigger: 'blur',
            type: 'string'
          }
        ]
      }
    },
    capacityRules: {
      type: Array,
      default: () => {
        return [
          {
            required: true,
            message: '容量不能为空',
            trigger: 'blur'
          }
        ]
      }
    },
    photoRules: {
      type: Array,
      default: () => {
        return [
          {
            required: true,
            message: '会议室缩略图不能为空',
            trigger: 'blur',
            type: 'string'
          }
        ]
      }
    },
    addressRules: {
      type: Array,
      default: () => {
        return [
          {
            required: true,
            message: '会议室地址不能为空',
            trigger: 'blur',
            type: 'string'
          }
        ]
      }
    },
    teamIdRules: {
      type: Array,
      default: () => {
        return [
          {
            required: true,
            message: '所属团队编号不能为空',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    form: {
      handler (val) {
        this.getEquipData(val.team_id)
      },
      deep: true
    }
  },
  mounted () {
    this.getEquipData(null)
  },
  data () {
    return {
      form: {
        name: '',
        capacity: '', // 容量
        equip: [],
        ischeck: true, // 预约是否需要审核
        address: '',
        team_id: '',
        photo: '/static/upload/photo/room/logo.png',
        state: true
      },
      isTeam: !getIsTeam(),
      isDevice: getIsTeam(),
      submit: false,
      equipData: [],
      photoImg: getImage('/static/upload/photo/room/logo.png'),
      upPhoto: {
        url: baseUrl + 'upload_room_photo',
        headers: {
          Authorization: ''
        }
      },
      checkOption: {
        indeterminate: false,
        checkAll: false
      }
    }
  },
  computed: {
    rules () {
      return {
        name: this.nameRules,
        capacity: this.capacityRules,
        photo: this.photoRules,
        address: this.addressRules,
        teamid: this.teamIdRules
      }
    }
  },
  methods: {
    handleSubmit () {
      this.$refs.addFrom.validate(valid => {
        if (valid) {
          this.submit = true
          this.$emit('on-success-valid', {
            name: this.form.name,
            capacity: this.form.capacity,
            address: this.form.address,
            photo: this.form.photo,
            equip: this.form.equip,
            team_id: this.form.team_id,
            ischeck: this.form.ischeck,
            state: this.form.state
          })
        } else {
          this.submit = false
        }
      })
    },
    stateChange (status) {
      this.form.state = status
    },
    ischeckChange (status) {
      this.form.ischeck = status
    },
    handleUploadSuccess (res, file, fileList) {
      if (res.code === 200) {
        this.form.photo = res.data.photo
        this.photoImg = getImage(res.data.photo)
        this.$Notice.success({
          title: res.message
        })
      } else {
        this.$Notice.warning({
          title: res.error
        })
      }
    },
    handleUploadErr (file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: '请上传 PNG,JPGE,GIF 等图片格式'
      })
    },
    handleUploadMaxSize () {
      this.$Notice.warning({
        title: '文件大写不正确',
        desc: '上传的图片不能大于20M'
      })
    },
    handleUploadBefore () {
      this.upPhoto.headers.Authorization = jwtToken()
      this.$Notice.success({
        title: '缩略图上传中...'
      })
    },
    success () {
      // 创建成功重新初始化
      this.form.name = ''
      this.form.capacity = ''
      this.form.equip = []
      this.form.address = ''
      this.form.photo = '/static/upload/photo/room/logo.png'
      this.form.ischeck = true
      this.form.state = true
      this.photoImg = getImage('/static/upload/photo/room/logo.png')
      this.submit = false
      this.checkOption.checkAll = false
      this.checkOption.indeterminate = false
    },
    fail () {
      this.submit = false
    },
    handleCheckAll () {
      if (this.checkOption.checkAll) {
        this.checkOption.checkAll = false
        this.checkOption.indeterminate = false
        this.form.equip = []
      } else {
        this.checkOption.checkAll = true
        this.checkOption.indeterminate = false
        this.equipData.forEach((item, index) => {
          this.form.equip.push(item.device_id)
        })
      }
    },
    checkAllGroupChange (data) {
      this.form.equip = data
      if (data.length === this.equipData.length) {
        // 全选
        this.checkOption.indeterminate = false
        this.checkOption.checkAll = true
      } else if (data.length > 0) {
        // 大于0
        this.checkOption.indeterminate = true
        this.checkOption.checkAll = false
      } else {
        this.checkOption.indeterminate = false
        this.checkOption.checkAll = false
      }
    },
    getEquipData (team_id) {
      getDeviceArr(team_id).then(res => {
        if (res.data.code === 200) {
          this.equipData = res.data.data.list
          if (res.data.data.list.length > 0) {
            this.isDevice = true
          } else {
            this.isDevice = false
          }
        } else {
          this.$Message.error(res.data.error)
          this.isDevice = false
        }
      }).catch(err => {
        console.log(err)
        this.$Message.error('获取设备失败')
        this.isDevice = false
      })
    }
  }
}
</script>
